<?php

namespace app\saas\service;

use app\common\logic\SmsLogic;
use app\common\model\trAdmin;
use app\saas\model\trMall;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\facade\Validate;

/**
 * Class Auth
 * @package app\admin\service
 * 管理员服务类
 */
class ManagerService
{
    private $returnData;
    private $params;
    private $adminId = 0;
    private $field = [
        "username" => "require", "password" => "require", "expired_time" => null, "app_count" => null, "remark" => null, "mobile" => "require"
    ]; //填入数据库需要存储的表字段
    private $fieldMsg = [
        "username" => "用户名", "password" => "密码", "expired_time" => "有效期", "app_count" => "小程序数量", "remark" => "备注", "mobile" => "手机号"
    ];
    private $data = [];
    private $isSuper = false;

    public function __construct($data, $param = null, $isSuper = false)
    {
        $this->returnData = $data;
        $this->params = $param;
        $this->adminId = request()->manageData["id"];
        $this->isSuper = $isSuper;
    }

    // 账户列表
    public function getAccountList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        if(!$this->isSuper){ // 不是超管，只显示自己的账号列表
            $filter[] = ["id", "=", $this->adminId];
        }
        $filter[] = ["status", "<>", 3];
        if(!empty($this->params['search'])){
            $filter[] = ['username|mobile', 'like', "%{$this->params["search"]}%"];
        }
        $data = trAdmin::field("id,username,remark,expired_time,app_count,mobile")
            ->where($filter)->order("create_time", "desc")
            ->paginate(array('page' => $page, 'list_rows' => $pageSize))->toArray();
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $data["data"] = Tools::transferFields($data["data"]);
            foreach ($data['data'] as &$item){
                $item["createCount"] = trMall::getCount(["manager_id" => $item["id"]]);
                if(!is_numeric($item["appCount"])){
                    $item["canCreate"] = "无限制";
                }else{
                    $item["canCreate"] = $item["appCount"] > $item["createCount"] ? $item["appCount"] - $item["createCount"] : 0;
                }
                $item["expiredTime"] = empty(trim($item["expiredTime"])) ? "永久" : date("Y-m-d", $item["expiredTime"]);
            }
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    public function getInfo(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "账户ID");
        }
        if(!$this->isSuper && $this->params['id'] != $this->adminId){
            return ErrorCode::code("customized", "您无权限操作");
        }
        $data = trAdmin::field("id,username,remark,expired_time,app_count,mobile")
            ->where("id", $this->params['id'])
            ->find();
        if($data){
            $data = Tools::transferFields($data->toArray());
            if(!empty($data["expiredTime"])){
                $data["expiredTime"] = date("Y-m-d", $data["expiredTime"]);
            }
            $this->returnData["data"] = $data;
        }else{
            $this->returnData["data"] = [];
        }
        return $this->returnData;
    }

    // 所有管理员
    public function getAll(){
        $data = trAdmin::field("id,username")->where("status", 1)->select();
        if($data){
            $data = Tools::transferFields($data->toArray());
            $this->returnData["data"] = $data;
        }else{
            $this->returnData["data"] = [];
        }
        return $this->returnData;
    }

    // 更新
    public function update(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "账户ID");
        }
        if(!trAdmin::where("id", $this->params["id"])->count()){
            return ErrorCode::code("customized", "账户不存在");
        }
        if(!$this->isSuper && $this->params["id"] != $this->adminId){
            return ErrorCode::code("customized", "您无权限操作");
        }
        unset($this->field["username"], $this->field["password"]);
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($this->params[$ks])) {
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            $this->data[$k] = isset($this->params[$ks]) ? trim($this->params[$ks]) : $v;
        }
        if(!Validate::isMobile($this->data["mobile"])){
            return ErrorCode::code("params_format", "手机号");
        }
        if(trAdmin::where("id", "<>", $this->params["id"])->where("mobile", $this->data["mobile"])->count()){
            return ErrorCode::code("mobile_exist");
        }
        if(request()->manageData["type"] == '3'){ // 由其它系统创建的账号不允许修改   && !$this->isSuper
            unset($this->data["expired_time"]);
        }else {
            $this->data["expired_time"] = !is_numeric($this->data["expired_time"]) ? strtotime($this->data["expired_time"]) : $this->data["expired_time"];
        }
        $res = trAdmin::where("id", $this->params["id"])->update($this->data);
        if($res || $res === 0){
            $this->returnData["msg"] = "更新账户成功";
        }else{
            $this->returnData = ErrorCode::code("customized", "更新账户失败");
        }
        return $this->returnData;
    }

    // 创建
    public function add(){
        if(!$this->isSuper){
            return ErrorCode::code("customized", "您无权限操作");
        }
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($this->params[$ks])) {
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            $this->data[$k] = isset($this->params[$ks]) ? trim($this->params[$ks]) : $v;
        }
        if(!Validate::isMobile($this->data["mobile"])){
            return ErrorCode::code("params_format", "手机号");
        }
        if(trAdmin::where("username", $this->data["username"])->count()){
            return ErrorCode::code("customized", "账号已存在");
        }
        if(trAdmin::where("mobile", $this->data["mobile"])->count()){
            return ErrorCode::code("mobile_exist");
        }
        $this->data["type"] = 2;
        $this->data["salt"] = local_salt();
        $this->data["password"] = generate_password($this->data["password"], $this->data["salt"]);
        $this->data["expired_time"] = $this->data["expired_time"] && !is_numeric($this->data["expired_time"]) ? strtotime($this->data["expired_time"]) : $this->data["expired_time"];
        $this->data['create_time'] = time();
        if(!trAdmin::insert($this->data)){
            $this->returnData = ErrorCode::code("customized", "添加账户失败");
        }
        return $this->returnData;
    }

    // 修改密码
    public function modifyPwd(){
        if(empty($this->params['id'])){
            $this->params['id'] = $this->adminId;
        }
        if(empty($this->params['password'])){
            return ErrorCode::code("params_not_exist", "新密码");
        }
        if(empty($this->params['confirmPassword'])){
            return ErrorCode::code("params_not_exist", "确认密码");
        }
        if($this->params['password'] != $this->params['confirmPassword']){
            return ErrorCode::code("customized", "确认密码不一致");
        }
        $adminData = trAdmin::where("id", $this->params["id"])->field("salt")->find();
        if(empty($adminData)){
            return ErrorCode::code("customized", "账户不存在");
        }
        if(!$this->isSuper && $this->params["id"] != $this->adminId){
            return ErrorCode::code("customized", "您无权限操作");
        }
        $this->data["password"] = generate_password(trim($this->params['password']), $adminData["salt"]);
        $res = trAdmin::where("id", $this->params["id"])->update($this->data);
        if($res || $res === 0){
            $this->returnData["msg"] = "修改密码成功";
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "修改密码失败";
        }
        return $this->returnData;
    }

    public function modifyMobile(){
        if(empty($this->params['id'])){
            $this->params['id'] = $this->adminId;
        }
        if(empty($this->params['mobile'])){
            return ErrorCode::code("params_not_exist", "新手机号");
        }
        if(empty($this->params['code'])){
            return ErrorCode::code("params_not_exist", "短信验证码");
        }
        if(!Validate::isMobile($this->params["mobile"])){
            return ErrorCode::code("params_format", "手机号");
        }
        if(trAdmin::where("id", "<>", $this->params["id"])->where("mobile", $this->params["mobile"])->count()){
            return ErrorCode::code("mobile_exist");
        }
        if(!$this->isSuper && $this->params["id"] != $this->adminId){
            return ErrorCode::code("customized", "您无权限操作");
        }
        $this->params["mobile"] = trim($this->params["mobile"]);
        if(!SmsLogic::checkValidateCode($this->params["code"], $this->params["mobile"], $msg)){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = $msg;
            return $this->returnData;
        }
        if(trAdmin::where("id", $this->params["id"])->update(["mobile" => $this->params["mobile"]])){
            $this->returnData["msg"] = "修改手机号成功";
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "修改手机号失败";
        }
        return $this->returnData;
    }

    // 删除
    public function delete(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "账户ID");
        }
        if(!trAdmin::where("id", $this->params["id"])->count()){
            return ErrorCode::code("customized", "账户不存在");
        }
        if($this->isSuper && $this->params["id"] == $this->adminId){
            return ErrorCode::code("customized", "不能删除超管账户");
        }
        if(!$this->isSuper && $this->params["id"] != $this->adminId){
            return ErrorCode::code("customized", "您无权限操作");
        }
        if(trAdmin::where("id", $this->params["id"])->delete()){
            $this->returnData["msg"] = "删除成功";
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "删除失败";
        }
        return $this->returnData;
    }
}